package com.song.promoter.core;

import java.io.File;
import java.io.FileWriter;
import java.util.LinkedList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

@SuppressWarnings("unchecked")
public class PromoterCore {
	private Log log = LogFactory.getLog(PromoterCore.class);
	private final static String WEBXMLFILE = "promoter.xml";
	
	public void parseXml2Client(){
		String filePath = ClassLoader.getSystemResource("").getPath() + WEBXMLFILE;
		SAXReader reader = new SAXReader();
		Document document = null;
		try {
			document = reader.read(filePath);
		} catch (DocumentException e) {
			log.error("解析promoter.xml文件出错...启动失败..",e);
			return ;
		}
		List<Node> webNodes = document.selectNodes("/webs/web");
		if(webNodes != null && webNodes.size()>0){
			for (Node webNode : webNodes) {
				if(null != webNode){
					PromoterControl.getInstance().addWebInfo(new WebInfo((Element)webNode));
				}
			}
		}
	}
	public static void main(String[] args) {
		PromoterCore pc = new PromoterCore();
		pc.parseXml2Client();
		LinkedList<WebInfo> webInfoList = PromoterControl.getInstance().getWebInfoList();
		if(webInfoList != null && webInfoList.size() > 0){
			for (WebInfo webInfo : webInfoList) {
				try {
					if(!webInfo.isSkip()){
						webInfo.login();
						HttpGet getMethod = new HttpGet("http://focus.tianya.cn/");
						HttpResponse resp = webInfo.getHttpClient().execute(getMethod);
						String content = EntityUtils.toString(resp.getEntity());
						FileWriter fw = new FileWriter(new File("D:/tianya.html"));
						fw.write(content);
						fw.flush();
						fw.close();
					}else{
						pc.log.info(webInfo.getWebName()+"跳过,未登录." + webInfo.isLoginSuccess());
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
}
